import React, { useState, useEffect } from 'react';
import Search from 'antd/lib/input/Search';
import { Space, Button, Table, message, Modal } from 'antd';

import { ColumnsType } from 'antd/lib/table';
import {
  getNotifyFlowList,
  offNotifyFlow,
  onlineNotifyFlow,
  queryNotifyFlowById,
  deleteNotifyFlow,
} from 'admin/servers/servers';
import { NotifyFlowInfo } from 'admin/schema/NotifyFlows';

import NotifyFlowPop from './components/NotifyFlowPop';
import NotifyFlowDetail from './components/NotifyFlowDetail';
import { useHistory } from 'react-router-dom';
import moment from 'moment';

/**
 * 通知流程列表
 */
const NotifyFlows: React.FC = () => {
  const history = useHistory();

  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  // 数据总数
  const [total, setTotal] = useState<number>(0);

  // 搜索内容
  const [searchText, setSearchText] = useState<string>('');
  const [tableData, setTableData] = useState<NotifyFlowInfo[]>([]);
  const [tableLoading, setTableLoading] = useState<boolean>(false);

  const [editVisible, setEditVisible] = useState<boolean>(false);
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [detailData, setDetailData] = useState<NotifyFlowInfo>({} as any);

  // 流程状态：(flowStatus 0:已上线，1：已下线)
  const states: any = {
    state: ['已上线', '已下线'],
    btnTxt: ['下线', '上线'],
    msg: ['流程已下线', '流程已上线'],
  };

  /**
   * Table列描述数据对象
   */
  const columns: ColumnsType<NotifyFlowInfo> = [
    {
      title: '序号',
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
      width: 70,
    },
    {
      title: '通知流程名称',
      dataIndex: 'flowName',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: (text, record, index) => {
        return moment(Number(text)).format('YYYY-MM-DD HH:mm');
      },
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'flowStatus',
      render: (text, record, index) => {
        return record.flowStatus ? states.state[1] : states.state[0];
      },
      width: 120,
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 350,
      render: (text, record, index) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleChangeStatus(record)}>
            {record.flowStatus ? states.btnTxt[1] : states.btnTxt[0]}
          </Button>
          <Button
            type="link"
            onClick={() => {
              history.push(
                `/webapp/outbound/ai/notifyFlows/notifySoundLibrary?notifyFlowId=${record.notifyFlowId}`
              );
            }}
          >
            录音库
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" onClick={() => handleDetail(record)}>
            详情
          </Button>
          <Button type="link" onClick={() => handleDelete(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const initData = async () => {
    setTableLoading(true);
    try {
      const res = await getNotifyFlowList({
        pageNo: current,
        pageSize: pageSize,
        flowName: searchText,
      });
      const { data, count } = res;
      setTableData(data || []);
      setTotal(Number(count) || 0);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  };

  useEffect(() => {
    initData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [current, pageSize, searchText]);

  /**
   * 搜索通知流程
   * @param text 搜索内容
   */
  const handleSearch = (text: string) => {
    text = text.trim();
    if (text !== searchText) {
      setSearchText(text);
      setCurrent(1);
    }
  };

  /**
   * 新增通知流程
   */
  const handleAdd = () => {
    setEditVisible(true);
  };

  /**
   * 新建编辑操作
   */
  const handleEdit = async (obj: NotifyFlowInfo) => {
    // 根据id请求数据，传入子组件
    try {
      const { data } = await queryNotifyFlowById(obj.notifyFlowId);
      setEditVisible(true);
      setDetailData(data);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  /**
   * 查看详情操作
   */
  const handleDetail = async (obj: NotifyFlowInfo) => {
    // 根据id请求数据，传入子组件
    try {
      const { data } = await queryNotifyFlowById(obj.notifyFlowId);
      setDetailVisible(true);
      setDetailData(data);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  /**
   * 重置列表
   */
  const resetTable = () => {
    if (current !== 1) {
      setCurrent(1);
      return;
    }
    initData();
  };

  /**
   * 上线、下线操作
   */
  const handleChangeStatus = async (obj: NotifyFlowInfo) => {
    try {
      let res;
      const state = obj.flowStatus || 0;
      if (state === 1) {
        // 当前下线，操作-上线
        res = await onlineNotifyFlow(obj.notifyFlowId);
      } else {
        // 当前上线，操作-下线
        res = await offNotifyFlow(obj.notifyFlowId);
      }
      if (res.code === 0) {
        message.success(states.msg[state]);
        // 刷新tab列表
        resetTable();
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };
  /**
   * 删除操作
   */
  const handleDelete = (obj: NotifyFlowInfo) => {
    Modal.confirm({
      title: '删除模板提示',
      content: '删除后无法恢复! 确认删除吗?',
      async onOk() {
        try {
          const res = await deleteNotifyFlow(obj.notifyFlowId);
          if (res.code === 0) {
            message.success(`删除成功`);
            // 刷新tab列表
            resetTable();
          }
        } catch (error) {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        }
      },
    });
  };

  return (
    <>
      <div className="mgr-header">
        <div className="mgr-header-left">
          <Search
            placeholder="请输入通知流程名称"
            enterButton="搜索"
            style={{ width: 300 }}
            onSearch={value => handleSearch(value.trim())}
            allowClear
          />
        </div>
        <div className="mgr-header-right">
          <Button type="primary" onClick={() => handleAdd()}>
            新建流程
          </Button>
        </div>
      </div>
      <div className="mgr-table">
        <Table
          scroll={{ x: '100%' }}
          loading={tableLoading}
          columns={columns}
          dataSource={tableData}
          rowKey="notifyFlowId"
          pagination={{
            current: current,
            total: total,
            pageSize: pageSize,
            showSizeChanger: true,
            // 改条数/页
            onShowSizeChange: (current, size) => {
              setPageSize(size);
            },
            // 改页码
            onChange: current => {
              setCurrent(current);
            },
            showTotal: total => `共${total}条`,
          }}
        />
      </div>
      {editVisible && (
        <NotifyFlowPop
          visible={editVisible}
          formData={detailData}
          callBack={(flag: boolean) => {
            setEditVisible(false);
            setDetailData({} as any);
            if (flag) {
              resetTable();
            }
          }}
        />
      )}
      <NotifyFlowDetail
        visible={detailVisible}
        formData={detailData}
        onClose={() => {
          setDetailVisible(false);
          setDetailData({} as any);
        }}
      />
    </>
  );
};

export default NotifyFlows;
